package com.toannv.gameController;

import com.toannv.card.card;

public class QuickSortCard {
	private card[] Cards;
	private int number;
	
	public void sortNumber(card[] values){
		if(values==null||values.length==0){
			return;
		}
		
		this.Cards = values;
		number = values.length;
		quicksortNumber(0, number-1);	
	}
	
	public void sortPoker(card[] values){
		if(values == null || values.length == 0){
			return;
		}
		
		this.Cards = values;
		number = values.length;
		quicksortPoker(0, number-1);
	}
	
	private void quicksortNumber(int low, int high){
		int i = low;
		int j = high;
		
		card pivot = new card(Cards[low+(high-low)/2]);
		
		while(i<=j){
			while((Cards[i].getNumber() < pivot.getNumber()) || 
					((Cards[i].getNumber() == pivot.getNumber())&&(Cards[i].getPoker() < pivot.getPoker()))){
				i++;
			}
			
			while((Cards[j].getNumber() > pivot.getNumber()) ||
					((Cards[j].getNumber() == pivot.getNumber())&&(Cards[j].getPoker() > pivot.getPoker()))){
				j--;
			}
			
			if(i<=j){
				exchange(i, j);
				i++;
				j--;
			}
		}
		
		if(low<j){
			quicksortNumber(low, j);
		}
		
		if(i<high){
			quicksortNumber(i, high);
		}
	}
	
	private void quicksortPoker(int low, int high){
		int i = low;
		int j = high;
		
		card pivot = new card(Cards[low+(high-low)/2]);
		
		while(i<=j){
			while((Cards[i].getPoker() < pivot.getPoker()) || 
					((Cards[i].getPoker() == pivot.getPoker())&&(Cards[i].getNumber() < pivot.getNumber()))){
				i++;
			}
			
			while((Cards[j].getPoker() > pivot.getPoker()) ||
					((Cards[j].getPoker() == pivot.getPoker())&&(Cards[j].getNumber() > pivot.getNumber()))){
				j--;
			}
			
			if(i<=j){
				exchange(i, j);
				i++;
				j--;
			}
		}
		
		if(low<j){
			quicksortPoker(low, j);
		}
		
		if(i<high){
			quicksortPoker(i, high);
		}
	}

	private void exchange(int i, int j) {
		// TODO Auto-generated method stub
		card temp = new card(Cards[i]);
		
		Cards[i].setNumber(Cards[j].getNumber());
		Cards[i].setPoker(Cards[j].getPoker());
		
		Cards[j].setNumber(temp.getNumber());
		Cards[j].setPoker(temp.getPoker());
	}
}
